export default (sequelize, DataTypes) => {
  const Essay = sequelize.define(
    'Essay',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
        comment: '作文唯一标识',
      },
      userId: {
        type: DataTypes.UUID,
        allowNull: false,
        field: 'user_id',
        references: {
          model: 'users',
          key: 'id',
        },
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE',
        comment: '所属用户ID',
      },
      title: {
        type: DataTypes.STRING(200),
        allowNull: true,
        comment: '作文标题',
      },
      content: {
        type: DataTypes.TEXT,
        allowNull: false,
        validate: {
          len: {
            args: [50, 5000],
            msg: '作文内容长度必须在50-5000个字符之间',
          },
        },
        comment: '作文内容',
      },
      imageUrl: {
        type: DataTypes.STRING(500),
        allowNull: true,
        field: 'image_url',
        comment: '作文图片URL（如果通过OCR提交）',
      },
      gradeLevel: {
        type: DataTypes.ENUM('primary', 'middle', 'high'),
        allowNull: false,
        field: 'grade_level',
        comment: '年级层次：primary-小学，middle-初中，high-高中',
      },
      status: {
        type: DataTypes.ENUM('pending', 'processing', 'completed', 'failed'),
        defaultValue: 'pending',
        allowNull: false,
        comment: '批改状态：pending-待批改，processing-批改中，completed-已完成，failed-失败',
      },
      score: {
        type: DataTypes.INTEGER,
        allowNull: true,
        validate: {
          min: 0,
          max: 100,
        },
        comment: 'AI批改评分（0-100分）',
      },
      correctionResult: {
        type: DataTypes.JSON,
        allowNull: true,
        field: 'correction_result',
        comment: 'AI批改结果（JSON格式，包含错误、建议等）',
      },
    },
    {
      tableName: 'essays',
      timestamps: true,
      underscored: true,
      indexes: [
        {
          name: 'idx_user_id',
          fields: ['user_id'],
        },
        {
          name: 'idx_status',
          fields: ['status'],
        },
        {
          name: 'idx_grade_level',
          fields: ['grade_level'],
        },
        {
          name: 'idx_created_at',
          fields: ['created_at'],
        },
        {
          name: 'idx_user_status',
          fields: ['user_id', 'status'],
        },
      ],
      comment: '作文表',
    }
  );

  // 定义关联关系
  Essay.associate = (models) => {
    Essay.belongsTo(models.User, {
      foreignKey: 'userId',
      as: 'user',
    });
  };

  // 实例方法：检查是否可以批改
  Essay.prototype.canCorrect = function () {
    return this.status === 'pending' || this.status === 'failed';
  };

  // 实例方法：标记为批改中
  Essay.prototype.markAsProcessing = async function () {
    this.status = 'processing';
    return await this.save();
  };

  // 实例方法：标记为已完成
  Essay.prototype.markAsCompleted = async function (score, result) {
    this.status = 'completed';
    this.score = score;
    this.correctionResult = result;
    return await this.save();
  };

  // 实例方法：标记为失败
  Essay.prototype.markAsFailed = async function () {
    this.status = 'failed';
    return await this.save();
  };

  return Essay;
};

